package com.pdstudio.carrecom.ui.fragment.account;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.LoginInfo;
import com.pdstudio.carrecom.bean.PhoneValideCode;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.bean.CarType.car;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.ui.activity.account.ActivityGoRegister;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class FragmentRegisterS4 extends Fragment {

	private View _view;
	private Activity _context;
	private Button _submit, mGetValidecode;
	private EditText mPhone, mValidecode;
	private Spinner mSelectCar;
	private ArrayAdapter<String> mSelectCarAd;
	ActivityGoRegister agr;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		_view = inflater.inflate(R.layout.fragment_account_register_s4,
				container, false);
		_context = getActivity();
		agr = (ActivityGoRegister) _context;
		initialView();
		return _view;
	}

	public void initialView() {
		// 获取车辆列表
		try {
			HttpExecuteJson http = new HttpExecuteJson(_context,
					mGetCarListListener);
			Map<String, Object> rps = new HashMap<String, Object>();
			http.get(ServiceHelper.CarList, rps);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mSelectCar = (Spinner) _view.findViewById(R.id.spin_re_selectcar);

		_submit = (Button) _view.findViewById(R.id.btn_rg_submit);
		_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(agr.mUserName.equals("")||agr.mUserName==null||agr.mPass.equals("")||agr.mPass==null){
					UIHelper.ToastMessage(_context, "请先在第一页输入用户名和设置密码");
				}else{
					if(mValidecode.getText()==null||mValidecode.getText().equals("")){
						UIHelper.ToastMessage(_context, "请先获取验证码");
					}else{
						try {
							_submit.setText("提交中...");
							HttpExecuteJson http = new HttpExecuteJson(_context, mRegisterPostListener);
							RequestParams rps=new RequestParams();
							rps.addBodyParameter("carname", StringUtils.utf8Encode(mSelectCar.getSelectedItem().toString()));
							rps.addBodyParameter("passwd", StringUtils.md5(agr.mPass.toString()));
							rps.addBodyParameter("name", agr.mUserName.toString());
							rps.addBodyParameter("phone",mPhone.getText().toString());
							http.post(ServiceHelper.Register, rps);
						} catch (Exception e) {
							e.printStackTrace();
							UIHelper.ToastMessage(_context, "注册失败："+e.getMessage());
						}
					}
				}
			}
		});

		mGetValidecode = (Button) _view.findViewById(R.id.btn_rg_getvalidecode);
		mGetValidecode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					if (mPhone.getText().toString().equals("")
							|| mPhone.getText() == null) {
						UIHelper.ToastMessage(_context, "手机号不能为空！");
					} else {
						HttpExecuteJson http = new HttpExecuteJson(_context,
								mLoginListener);
						RequestParams rps = new RequestParams();
						http.post(ServiceHelper.RegisterCode + "/"
								+ mPhone.getText().toString(), rps);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
		mPhone = (EditText) _view.findViewById(R.id.et_rg_phonenum);
		mValidecode = (EditText) _view.findViewById(R.id.et_rg_validecode);
	}

	/*
	 * 获取验证码监听
	 */
	private httpReturnJson mLoginListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(_context, "获取验证码失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(_context, "获取验证码失败");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJson(result);
		}
	};

	/*
	 * 获取验证码
	 */
	private void DoJson(String json) {
		PhoneValideCode edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<PhoneValideCode>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				// 原本在initview的代码放在这下面
				try {
					mValidecode.setText(edv.code);

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				UIHelper.ToastMessage(_context, "获取验证码失败");

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(_context, "获取验证码失败：" + e.getMessage());
		}

	}

	/*
	 * 获取车辆数据
	 */
	private void DoJsonSc(String json) {
		// String[] items={"我的爱车是：","大众","奔驰","宝马","奥迪","标致"};
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<ResultInfo>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				// 原本在initview的代码放在这下面
				try {
					// List<car> cars=(ArrayList<car>)edv.data;

					List<car> cars = JsonUtil.fromJsonArray(
							edv.data.toString(), car.class);

					String[] items = new String[cars.size() + 1];
					car c = (car) cars.get(0);
					items[0] = c.name;
					for (int i = 1; i < (cars.size() + 1); i++) {
						items[i] = c.name;
					}

					mSelectCarAd = new ArrayAdapter<String>(_context,
							android.R.layout.simple_spinner_item, items);
					mSelectCar.setAdapter(mSelectCarAd);
				} catch (Exception e) {
					e.printStackTrace();
					UIHelper.ToastMessage(_context, "获取车辆列表失败");
				}
			} else {
				UIHelper.ToastMessage(_context, "获取车辆列表失败");

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(_context, "获取车辆列表失败");
		}

	}

	private httpReturnJson mGetCarListListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(_context, "获取车辆列表失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(_context, "获取车辆列表失败");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJsonSc(result);
		}
	};
	
	private void DoJsonRp(String json){
		_submit.setText("完成");
		LoginInfo edv = null;
		try {
			edv = new Gson().fromJson(json,
					new TypeToken<LoginInfo>() {
					}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				//原本在initview的代码放在这下面
				try{
					
					UIHelper.ToastMessage(_context, "注册账号成功，用户名为："+agr.mUserName);
					_context.finish();
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				UIHelper.ToastMessage(_context, "注册失败");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(_context, "注册失败");
		}

	}
	
	private httpReturnJson mRegisterPostListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(_context, "注册失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(_context, "注册失败");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJsonRp(result);
		}
	};

}
